using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace CloudApiServer.Services;

/// <summary>
/// 冲正服务
/// </summary>
public class FsiReverseService
{
    /// <summary>
    /// 2601冲正服务
    /// </summary>
    /// <param name="fsiRequest">入参</param>
    /// <param name="ControllerName">来源控制器名称</param>
    /// <returns>出参</returns>
    /// <exception cref="Exception"></exception>
    public async Task<bool> RevsMethod(FsiRequestHeader<InputRevsMethod> fsiRequest, string ControllerName)
    {
        try
        {
            string fixmedins_code = fsiRequest.fixmedins_code;
            string psn_no = fsiRequest.Input.data.psn_no;
            string omsgid = fsiRequest.Input.data.omsgid;
            if (fsiRequest.Input.data.oinfno.Length<4)
            {
                throw new Exception($"参数校验失败：传入的原交易编号omsgid【{fsiRequest.Input.data.oinfno}】参数长度不足4！，请检查入参！");
            }
            string oinfno = fsiRequest.Input.data.oinfno.Substring(0, 4);
            if (string.IsNullOrEmpty(fixmedins_code) || string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(omsgid) )
            {
                throw new Exception("参数校验失败：传入的机构编码|结算id|人员编号|原发送方报文id为空，请检查入参！");
            }

            if (oinfno.Length<4)
            {
                throw new Exception($"参数校验失败：传入的原发送方报文id【{oinfno}】长度不足为4，请检查入参！");
            }

            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            if (oinfno.Substring(0, 4) == "2102" || oinfno.Substring(0, 4) == "2103" )
            {
                string query =
                    "select * from fsi_drugstore_order where order_canceltype =0 and LEFT(infno, 4)=@infno and psn_no=@psn_no and msgid=@msgid";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@infno", oinfno),
                    new MySqlParameter("@psn_no", psn_no),
                    new MySqlParameter("@msgid", omsgid)
                };
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                if (dt.Rows.Count != 1)
                {
                    if (FsiDatainfo.stateRevsMethodDataVerify)
                    {
                        throw new Exception($"查询未冲正的结算记录失败！根据传入的原发送方报文ID【{omsgid}】接口编号【{oinfno}】人员编号【{psn_no}】查询到的总数为：{dt.Rows.Count}，不符合预设的要求！");
                    }
                }
                query = "update fsi_drugstore_order set order_canceltype = 1  and LEFT(infno, 4)=@infno and psn_no=@psn_no and msgid=@msgid";
                int count =  await MySqlHelper.ExecuteNonQueryAsync(connectionString, query, parameter);
                if (count == 0 )
                {
                    if (FsiDatainfo.stateRevsMethodDataVerify)
                    {
                        throw new Exception(
                            $"根据传入的原发送方报文ID【{omsgid}】接口编号【{oinfno}】人员编号【{psn_no}】查询到了相关结算记录但冲正返回受到影响的行数为0，请联系管理员排查！");
                    }
                }
            }
            else
            {
                throw new Exception($"传入的接口编号【{oinfno}】不支持冲正！暂只支持2102、2103接口编号的冲正！");
            }

            return true;
        }
        catch (Exception ex)
        {
            LogHelper.Error($"[FsiReverseService.RevsMethod]冲正服务异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
            throw;
        }
    }
}